/* Copyright (c) 2004-2024 peigen.info. All rights reserved. */

package info.peigen.hotpot.common.service.base.test;

import cn.hutool.core.util.RandomUtil;
import info.peigen.hotpot.common.service.base.test.mock.ServiceTestMockContextThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.noear.solon.core.handle.ContextEmpty;
import org.noear.solon.core.handle.ContextUtil;

import java.util.Properties;

/**
 * <b>(ServiceTestBase)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/8/17
 */
@SuppressWarnings("unused")
@Slf4j
public class ServiceTestBase extends RepositoryTestBase {
    // 设置测试用例随机端口
    static {
        Properties properties = System.getProperties();
        properties.setProperty("server.port", String.valueOf(RandomUtil.randomInt(9999, 25535)));
    }

    @BeforeEach
    void settingContext() {
        ContextUtil.currentSet(new ContextEmpty());
    }

    public void executeTest(ServiceTestContext serviceTestContext, ServiceTestInvoke invoke) {
        // 0. callStartTime
        long callStartTime = System.currentTimeMillis();

        try {
            // 1. cleanData
            invoke.cleanData();

            // 2. initData
            invoke.initData(serviceTestContext);

            // 3. callService
            invoke.callService(serviceTestContext);

            // 4. printLog
            invoke.printLog(serviceTestContext);

            // 5. resultAssert
            p(serviceTestContext);
            invoke.resultAssert(serviceTestContext);

            // 6. dataAssert
            invoke.dataAssert(serviceTestContext);
        } catch (Exception e) {
            // 7. exception
            invoke.exceptionAssert(e, serviceTestContext);
            p(serviceTestContext);
            invoke.resultAssert(serviceTestContext);
        }
        ServiceTestMockContextThreadLocal.destroy();
        log.info("测试耗时:{}ms", System.currentTimeMillis() - callStartTime);
    }
}